package com.tuanzi.loan.web.bean.channel;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.repository.common.impl.SecondaryChannelGroupRepository;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.response.channel.SecondaryChannelGroupResponse;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.CHANNEL_GROUP;

@Debug
@Component
@ViewScoped
public class SecondaryChannelGroupInfoBean extends JSFInfoBean<SecondaryChannelGroupResponse> {

    @Autowired
    private SecondaryChannelGroupRepository secondaryChannelGroupRepository;

    @PostConstruct
    private void init() {
        $ = new SecondaryChannelGroupResponse();
    }

    public void onSave() {
        if (StringUtils.isEmpty($.getChannelName())) {
            addErrorMessage("二级渠道分类名称不能为空");
            return;
        }
        if ($.getPrimaryChannelGroup() == null) {
            addErrorMessage("渠道分类不能为空");
            return;
        }
        if (secondaryChannelGroupRepository.existByChannelName($.getChannelName())) {
            addErrorMessage("该二级渠道分类已存在");
            return;
        }

        secondaryChannelGroupRepository.insert($);
        addSuccessfullyMessage();
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(CHANNEL_GROUP);
    }

}
